<?php

namespace Common\Model;

/**
 * 自订单表
 * @modify trainyao 2016-01-05 创建
 * @index orderinfo_id (`orderinfo_id`)
 * @index hotel_room_status(`hotelentity_id`, `roominfo_id`, `status`)
 */
Class OrderRoomModel extends BaseModel {

    protected $trueTableName = 'tb_order_room';
    private $redisHash = 100;

    protected function _before_insert(&$data, $options) {
        $data['creator'] = getUserId();
    }

    protected function _before_update(&$data, $options) {
        
    }

    /**
     * 根据房间id查询子订单
     * @modify trainyao 2016-01-05  创建
     * @modify Paddy 2016-11-05  增加排序
     * @param  integer    $hotelId    客栈id
     * @param  mixin    $roomId 自订单id(s)
     * @param  array  $status     订单状态
     * @return array               自订单信息
     */
    public function getInfoByHotelRoom($hotelId, $roomId = null, $status = null) {
        $option = array(
            'hotelentity_id' => $hotelId,
        );
        if (!empty($roomId)) {
            if (is_array($roomId)) {
                $roomId = implode(',', $roomId);
            }
            if (strpos($roomId, ',') !== false) {
                $option['roominfo_id'] = array('in', $roomId);
            } else {
                $option['roominfo_id'] = $roomId;
            }
        }
        if (!empty($status)) {
            $option['status'] = array('in', $status);
        }

        // 读取redis自订单数据调整订单,活跃订单调整已过期->已预订,历史订单调整已过期->删除
        // ...
        $field = 'id,hotelentity_id,orderinfo_id,roominfo_id,status,payment,startdate,enddate,checkindate,printcheckoutdate,checkoutdate,roomtype_name,roominfo_name,roominfo_from,createtime,creator,night,realnight,hour,month,ismidnightorder,minusprice';
        $data = $this->where($option)->field($field)->order('createtime desc,id desc')->select();

        return empty($data) ? array() : $data;
    }

    /**
     * 根据id获取子订单
     * @modify trainyao 2016-01-19 创建
     * @param  mixin   $id        子订单id
     * @return array              子订单信息数组
     */
    public function getInfo($id, $switchStatus = false, $startDate = null, $endDate = null) {
        $option = array();
        if (is_array($id)) {
            $id = implode(',', $id);
        }
        if (strpos($id, ',') !== false) {
            $option['id'] = array('in', $id);
        } else {
            $option['id'] = $id;
        }
        if ($switchStatus) {
            $option['status'] = array('in', '2,3');
        }
        if(!is_null($startDate) && !is_null($endDate)){
            $option['startdate'] =  array('between',[$startDate, $endDate]);
        }

        $data = $this->where($option)->select();

        return empty($data) ? array() : $data;
    }

    /**
     * 根据父订单获取子订单
     * @modify trainyao 2016-01-05 创建
     * @param  mixin   $orderId   父订单id(s)
     * @param  mixin   $brief     是否获取概要信息,默认为true
     * @return array              子订单信息
     */
    public function getInfoByOrder($orderId, $brief = true) {
        $option = array();
        if (is_array($orderId)) {
            $orderId = implode(',', $orderId);
        }

        if (strpos($orderId, ',') !== false) {
            $option['orderinfo_id'] = array('in', $orderId);
        } else {
            $option['orderinfo_id'] = $orderId;
        }

        $field = 'id,hotelentity_id,orderinfo_id,roominfo_id,startdate,enddate,checkindate,printcheckoutdate,checkoutdate,status,creator,night,realnight,hour,month,ismidnightorder,minusprice';
        if ($brief !== true) {
            $field = 'id,hotelentity_id,orderinfo_id,roominfo_id,status,payment,startdate,enddate,checkindate,printcheckoutdate,checkoutdate,roomtype_name,roominfo_name,roominfo_from,creator,createtime,night,realnight,hour,month,ismidnightorder,minusprice';
        }

        $data = $this->where($option)->field($field)->select();
        return empty($data) ? array() : $data;
    }

    /**
     * 根据父订单获取子订单
     * @modify trainyao 2016-01-05 创建
     * @param  mixin   $orderId   父订单id(s)
     * @param  mixin   $brief     是否获取概要信息,默认为true
     * @return array              子订单信息
     */
    public function getAllInfoByOrder($orderId) {
        $option = array(
            'status' => array('in', '2,3'),
        );
        if (is_array($orderId)) {
            $orderId = implode(',', $orderId);
        }

        if (strpos($orderId, ',') !== false) {
            $option['orderinfo_id'] = array('in', $orderId);
        } else {
            $option['orderinfo_id'] = $orderId;
        }

        $field = 'id';

        $data = $this->where($option)->field($field)->select();
        return empty($data) ? array() : $data;
    }

    /**
     * 根据子订单获取款项
     * @modify trainyao 2016-01-05 创建
     * @param  mixin   $orderRoomId   订单id
     * @return array              子订单信息
     */
    public function getPayment($orderRoomId) {
        $option = [
            'id' => $orderRoomId,
        ];

        $field = 'id,payment';
        $data = $this->where($option)->field($field)->find();
        return empty($data) ? array() : $data;
    }
    /**
     * 根据开始结束时间获取房间的订单
     * @modify trainyao 2016-05-04 创建
     * @param  integer   $hotelId   客栈ID
     * @param  mixin   $roomId    房间ID(s)
     * @param  string   $startDate 入住日期
     * @param  string   $endDate   实际退房日期
     * @param  string   $status    子订单状态
     * @return array              信息数组
     */
    public function getInfoByHotelRoomDate($hotelId, $roomId = null, $startDate = null, $endDate = null, $status = null, $splitOrder = false) {
        $option = array(
            'hotelentity_id' => $hotelId,
        );
        if (!empty($roomId)) {
            if (is_array($roomId)) {
                $roomId = implode(',', $roomId);
            }
            if (strpos($roomId, ',') !== false) {
                $option['roominfo_id'] = array('in', $roomId);
            } else {
                $option['roominfo_id'] = $roomId;
            }
        }
        if (!is_null($status)) {
            $option['status'] = array('in', $status);
        } else {
            $option['status'] = array('in', array(ORDER_BOOKED, ORDER_PAYED, ORDER_CHECKINED, ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED));

        }
        $dateOptonOpposite = array();
        if (!is_null($startDate)) {
            if ($splitOrder) {
                $option['ismidnightorder'] = 1;
                array_push($dateOptonOpposite, '(checkoutdate < "' . $startDate . '")');
            } else {
                array_push($dateOptonOpposite, '(checkoutdate <= "' . $startDate . '")');
            }
        }
        if (!is_null($endDate)) {
            array_push($dateOptonOpposite, '(startdate >= "' . $endDate . '" )');
        }
        $dateOptonOpposite = implode(' or ', $dateOptonOpposite);


        // 读取redis自订单数据调整订单,活跃订单调整已过期->已预订,历史订单调整已过期->删除
        // ...
        if (empty($dateOptonOpposite)) {
            $data = $this->where($option)->select();
        } else {
            $data = $this->where($option)->where('not (' . $dateOptonOpposite . ')')->select();
        }

        return empty($data) ? array() : $data;
    }

    /**
     * 修改子订单
     * @modify songanwei 2016-01-07
     * @param integer $hotelId      客栈ID
     * @param integer $orderRoomId  订单房间ID
     * @param integer $orderId 父订单ID
     * @param integer $roomId 房间ID
     * @param integer $payment 金额
     * @param date $startDate 入住开始日期
     * @param date $endDate 入住结束日期
     * @param string $roomType 房型名称
     * @param string $roomName 房间号
     * @param integer $nights 入住几晚
     * @param string $checkoutDate     实际退房日期
     * @param integer $realNight        实住晚数
     * @return type
     */
    public function saveInfo($hotelId, $orderRoomId, $orderId, $roomId, $payment, $startDate, $endDate, $roomType, $roomName, $nights, $checkoutDate = null, $realNight = null, $roomFrom = 0, $hour = 0, $month = 0) {
        $options = array(
            'hotelentity_id' => $hotelId,
            'orderinfo_id' => $orderId,
            'roominfo_id' => $roomId,
            'payment' => $payment,
            'startdate' => $startDate,
            'enddate' => $endDate,
            'roomtype_name' => $roomType,
            'roominfo_name' => $roomName,
            'night' => $nights,
        );
        if (!empty($roomFrom)) {
            $options['roominfo_from'] = $roomFrom;
        }
        if (!is_null($realNight)) {
            $options['realnight'] = $realNight;
        }
        if (!is_null($checkoutDate)) {
            $options['checkoutdate'] = $checkoutDate;
        }
        if (!empty($hour)) {
            $options['hour'] = $hour;
        }
        if (!empty($month)) {
            $options['month'] = $month;
        }
        $result = $this->where(array('id' => $orderRoomId))->save($options);

        return $result === false ? false : true;
    }

    /**
     * 保存实际入住数据
     * @modify trainyao 2016-01-23  创建
     * @param  integer   $subOrderId 子订单id
     * @param  string   $checkoutDate      实际退房日期字符串
     * @param  integer   $realNight  实际住多少晚
     * @return boolean 执行结果
     */
    public function setCheckoutData($subOrderId, $checkoutDate = null, $realNight = null, $checkInDate = null, $printCheckOutDate = null) {
        $option = array(
            'id' => $subOrderId,
        );
        /*$data = array(
            'checkoutdate' => $checkoutDate,
            'realnight' => $realNight,
        );*/
        $data = array();
        if (!is_null($checkoutDate)) {
            $data['checkoutdate'] = $checkoutDate;
        }
        if (!is_null($realNight)) {
            $data['realnight'] = $realNight;
        }
        if (!is_null($checkInDate)) {
            $data['checkindate'] = $checkInDate;
        }
        if (!is_null($printCheckOutDate)) {
            $data['printcheckoutdate'] = $printCheckOutDate;
        }

        return $this->where($option)->save($data) === false ? false : true;
    }

    /**
     * 获取redis里的活跃子订单记录
     * @modify trainyao 2016-05-12    创建
     * @param  integer   $hotelId      客栈ID
     * @param  integer   $roomId       房间ID
     * @param  integer   $orderRoomIds 子订单ID
     * @param  integer   $expireMinute 订单几分钟后过期
     * @return boolean                 执行结果
     */
    public function saveInfoInRedis($hotelId, $roomId, $orderRoomId, $expireMinute) {
        if (empty($this->redisUtil)) {
            $this->redisUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
        }
        $this->redisUtil->db(C('REDIS_ORDER_DB'))->table('orderRoom');

        $expireTime = time() + ((int)$expireMinute * 60);
        $addResult = $this->redisUtil->add(array(
            'hotelentity_id' => $hotelId,
            'roominfo_id' => $roomId,
            'orderroom_id' => $orderRoomId,
            'orderOutdateTime' => date('Y-m-d H:i:s', $expireTime),

        ), $hotelId . '_' . $roomId . '_' . $orderRoomId, $expireTime);

        return empty($addResult) ? false : true;
    }
        
    /**
     * 获取redis里的活跃子订单记录
     * @modify trainyao 2016-01-07   创建
     * @param  integer   $hotelId     客栈id
     * @param  mixin   $roomId      房间ID
     * @param  mixin   $orderRoomIds 子订单id(s)
     * @return mixin                活跃子订单数据数组,查询失败返回false
     */
    public function getInfoInRedisByHotelRoomOrderRoom($hotelId = null, $roomId = null, $orderRoomIds = null) {
        // 处理默认情况,不传参数取出所有数据
        if (is_null($hotelId)) {
            $hotelId = array('*');
        } else {
            if (!is_array($hotelId)) {
                $hotelId = explode(',', $hotelId);
            }
            if (!is_array($hotelId)) {
                return false;
            }
        }
        if (is_null($orderRoomIds)) {
            $orderRoomIds = array('*');
        } else {
            if (!is_array($orderRoomIds)) {
                $orderRoomIds = explode(',', $orderRoomIds);
            }
            if (!is_array($orderRoomIds)) {
                return false;
            }
        }
        if (is_null($roomId)) {
            $roomId = array('*');
        } else {
            if (!is_array($roomId)) {
                $roomId = explode(',', $roomId);
            }
            if (!is_array($roomId)) {
                return false;
            }
        }

        // 取数据
        if (empty($this->redisUtil)) {
            $this->redisUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
        }
        $this->redisUtil->db(C('REDIS_ORDER_DB'))->table('orderRoom');
        $result = array();
        foreach ($hotelId as $hotelIdItem) {
            foreach ($roomId as $roomIdItem) {
                foreach ($orderRoomIds as $orderRoomIdItem) {
                    $resultTmp = $this->redisUtil->select($hotelIdItem . '_' . $roomIdItem . '_' . $orderRoomIdItem);
                    if (!empty($resultTmp)) {
                        $result = array_merge($result, $resultTmp);
                    }
                }
                unset($orderRoomIdItem);
            }
            unset($roomIdItem);
        }
        unset($hotelIdItem);

        if (empty($result)) {
            return array();
        }
        return $result;
    }

    /**
     * 返回每一天的子订单数据
     * @modify songanwei 2016-01-25
     * @param integer $hotelId  客栈ID
     * @param date $date  查询日期
     * @return type
     */
    public function getInfoByHotelDay($hotelId, $date) {
        $where['hotelentity_id'] = $hotelId;
        $where['UNIX_TIMESTAMP(startdate)'] = array('elt', strtotime($date));
        $where['UNIX_TIMESTAMP(checkoutdate)'] = array('gt', strtotime($date));
        $where['month'] = array('EQ', 0);
        $where['status'] = array('IN', ORDER_BOOKED . ',' . ORDER_PAYED . ',' . ORDER_CHECKOUTED . ',' . ORDER_CHECKINED);
        return $this->where($where)->select();
    }

    /**
     * 返回每一天的子订单数据
     * @modify songanwei 2016-01-25
     * @param integer $hotelId  客栈ID
     * @param date $date  查询日期
     * @return type
     */
    public function getMidnightOrder($hotelId, $date) {
        $where['hotelentity_id'] = $hotelId;
        $where['ismidnightorder'] = 1;
        $where['UNIX_TIMESTAMP(startdate)'] = array('elt', strtotime($date));
        $where['UNIX_TIMESTAMP(checkoutdate)'] = array('egt', strtotime($date));
        $where['month'] = array('EQ', 0);
        $where['status'] = array('IN', ORDER_BOOKED . ',' . ORDER_PAYED . ',' . ORDER_CHECKINED);
        return $this->where($where)->select();
    }

    /**
     * 返回每一天的子订单数据
     * @modify zhangzhen 2017-06-05
     * @param integer $hotelId  客栈ID
     * @param date $date  查询日期
     * @return type
     */
    public function getInfoByHotelHour($hotelId, $date) {
        $where['hotelentity_id'] = $hotelId;
        $where['UNIX_TIMESTAMP(startdate)'] = array('gt', strtotime($date));
        $where['UNIX_TIMESTAMP(checkoutdate)'] = array('lt', strtotime($date.' 23:59:59'));
        $where['status'] = array('IN', ORDER_BOOKED . ',' . ORDER_PAYED . ',' . ORDER_CHECKOUTED . ',' . ORDER_CHECKINED);
        return $this->where($where)->select();
    }

    /**
     * 返回每一天的子订单数据
     * @modify zhangzhen 2017-8-15
     * @param integer $hotelId  客栈ID
     * @param date $date  查询日期
     * @return mixed
     */
    public function getInfoByHotelMonth($hotelId, $date) {
        $where['hotelentity_id'] = $hotelId;
        $where['UNIX_TIMESTAMP(startdate)'] = array('elt', strtotime($date));
        $where['UNIX_TIMESTAMP(checkoutdate)'] = array('gt', strtotime($date));
        $where['status'] = array('IN', ORDER_BOOKED . ',' . ORDER_PAYED . ',' . ORDER_CHECKOUTED . ',' . ORDER_CHECKINED);
        $where['month'] = array('NEQ', 0);
        return $this->where($where)->select();
    }

    /**
     * 返回每月的子订单数据
     * @modify zhangzhen 2017-8-15
     * @param integer $hotelId 客栈ID
     * @param $startDate
     * @param $endDate
     * @return mixed
     */
    public function getInfoBetweenHotelMonth($hotelId, $startDate, $endDate) {
        $where['hotelentity_id'] = $hotelId;
        $where['startdate'] = ['between',[$startDate, $endDate]];
        $where['status'] = array('IN', [ORDER_BOOKED, ORDER_PAYED , ORDER_CHECKINED, ORDER_CHECKOUTED ]);
        $where['month'] = array('NEQ', 0);
        $where['realnight'] = array('NEQ', 0);
        return $this->where($where)->select();
    }

    /**
     * 设置订单状态
     * @modify trainyao 2016-01-06 创建
     * @param  mixin   $id        子订单id(s)
     * @param  integer   $status    订单状态,constant里值
     * @return boolean              执行结果
     */
    public function setStatus($id, $status) {
        $option = array();
        if (is_array($id)) {
            $id = implode(',', $id);
        }

        if (strpos($id, ',') !== false) {
            $option['id'] = array('in', $id);
        } else {
            $option['id'] = $id;
        }
        $data = array(
            'status' => $status,
        );

        return $this->where($option)->save($data) === false ? false : true;
    }

    /**
     * 添加多条子订单
     * @modify trainyao 2016-02-02 创建
     * @param  array   $infoArray 子订单信息数组
     * @return boolean 执行结果
     */
    public function addInfo($infoArray) {
        $result = $this->addAll($infoArray);
        return empty($result) ? false : $result;
    }

    /**
     * 添加新订单数据到redis
     * @modify trainyao 2016-01-18 创建
     * @param  integer   $hotelId   客栈id
     * @param  integer   $orderRoomId   子订单id
     * @param  array   $dataArray redis信息数据
     * @return  boolean     执行结果
     */
    public function addInfoInRedis($hotelId, $orderRoomId, $dataArray) {
        if (empty($this->redisHelperUtil)) {
            $this->redisHelperUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
        }
        $this->redisHelperUtil->db(C('REDIS_ROOM_DB'));

        $addResult = $this->redisHelperUtil->table('neworder')->hMSet($hotelId . '_' . $orderRoomId . rand(),
                array(
            'value' => 'a:' . $dataValue['id'] . ':' . $dataValue['order'] . ':' .
            $dataValue['room'] . ':' . $dataValue['roomtype'] . ':' .
            $dataValue['roomname'] . ':' . $dataValue['start'] . ':' .
            $dataValue['end'] . ':' . $dataValue['pay'] . ':' .
            $dataValue['night'] . ':' . $dataValue['status'] . ':' .
            $dataValue['price'] . ':' . $dataValue['receipt'] . ':' .
            $dataValue['deposit'] . ':' . $dataValue['name'] . ':' .
            $dataValue['mobile'] . ':' . $dataValue['identity'] . ':' .
            $dataValue['remark'] . ':' . $dataValue['channelname']
        ));

        return empty($addResult) ? false : true;
    }

    /**
     * 获取房间入住时间为某开始时间或结束时间的订单
     * @modify trainyao 2016-04-08 创建
     * @param  integer   $hotelId   客栈ID
     * @param  mixin   $roomId    房间ID(s)
     * @param  string   $startDate 开始日期
     * @param  string   $endDate   结束日期
     * @return array              数据数组
     */
    public function getInfoByRoomDate($hotelId, $roomId, $startDate = null, $endDate = null) {
        $option = array(
            'hotelentity_id' => $hotelId,
        );
        if (is_array($roomId)) {
            $roomId = implode(',', $roomId);
        }

        if (strpos($roomId, ',') === false) {
            $option['roominfo_id'] = $roomId;
        } else {
            $option['roominfo_id'] = array('in', $roomId);
        }
        if (!is_null($startDate)) {
            $option['startdate'] = $startDate;
        }
        if (!is_null($endDate)) {
            $option['enddate'] = $endDate;
        }

        $data = $this->where($option)->select();
        return empty($data) ? array() : $data;
    }
}
